package com.seya.calculite.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.util.List;
import java.util.Locale;


public class SplashScreenActivity extends Activity {

    SharedPreferences prefs;
    Context c;
    Boolean location_state = false;
    Boolean network_state;
    GPSTracker gps;
    String location;
    double longitude, latitude;
    ProgressDialog pDialog;

    public static boolean loggingOut = false;
    public static final String[] login_ids= new String[]{"001","002","003"};
    public static final String LOGIN_ID = "loginid";
    public static final String SHARED_PREFERENCES_NAME = "com.seya.calculite.settings";
    public static final String START_LATITUDE = "slatitude";
    public static final String START_LONGITUDE = "slongitude";
    public static final String END_LATITUDE = "slatitude";
    public static final String END_LONGITUDE = "slongitude";
    public static final String VEHICLE = "vehicle";
    public static final String COMPANY = "company";
    public static final String KILOMETER = "kilometer";
    public static final String TOTAL_TIME = "totaltime";
    public static final String T_HOURS = "tHours";
    public static final String T_MINUTES = "tMinutes";
    public static final String T_SECONDS = "tSeconds";
    public static final String TAG = "tag";
    public static final String START_LOCATION = "slocation";
    public static final String END_LOCATION = "elocation";
    public static final String TIMER_SERVICE = "timerservice";

    private static int SPLASH_TIME_OUT = 3000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        overridePendingTransition(R.anim.activity_open_translate,R.anim.activity_close_scale);
        setContentView(R.layout.activity_splash_screen);
        FontHelper.applyFont(this, findViewById(R.id.activity_main_root), "RobotoLight.ttf");

        c = this;

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                loggingOut = false;
                String login_id;
                gps = new GPSTracker(SplashScreenActivity.this);
                prefs = c.getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE);
                login_id = prefs.getString(LOGIN_ID,"null");
                //Save it as a float since SharedPreferences can't deal with doubles
                //Toast.makeText(getApplicationContext(),login_id,Toast.LENGTH_SHORT).show();
                if(login_id == "null") {
                    Intent i = new Intent(SplashScreenActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                } else {
                    if (isMyServiceRunning(TimerService.class)) {
                        Intent i = new Intent(SplashScreenActivity.this, ProcessActivity.class);
                        startActivity(i);
                        finish();
                    }
                    else {
                            if (gps.canGetLocation()) {
                                location_state = true;
                                latitude = gps.getLatitude();
                                longitude = gps.getLongitude();
                            }
                        network_state = isNetworkOnline();
                        if (network_state && location_state) {
                            new GetLocation().execute();
                        } else {
                            Toast.makeText(c, "Turn ON Network and Location to proceed",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }

            }
        },SPLASH_TIME_OUT);
    }

    private class GetLocation extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(SplashScreenActivity.this);
            pDialog.setMessage("Please wait...Getting Location");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            if(gps.canGetLocation()){
                Log.d("LOC_long", Double.toString(longitude));
                Log.d("LOC_lat",Double.toString(latitude));
                prefs = c.getSharedPreferences(SplashScreenActivity.SHARED_PREFERENCES_NAME,
                        MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                //Save it as a float since SharedPreferences can't deal with doubles
                editor.putString(SplashScreenActivity.START_LATITUDE,
                        Double.toString(latitude));
                editor.putString(SplashScreenActivity.START_LONGITUDE,
                        Double.toString(longitude));
                editor.commit();
                try {
                    Geocoder geocoder = new Geocoder(getApplicationContext(),
                            Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addresses.size() > 0) {
                        location = addresses.get(0).getThoroughfare() + ", " +
                                addresses.get(0).getSubLocality() + ", " +
                                addresses.get(0).getLocality() + ", " +
                                addresses.get(0).getPostalCode();
                    }
                }
                catch (Exception e) {
                    location_state = false;
                }
            }
            else {
                location_state = false;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (pDialog.isShowing())
                pDialog.dismiss();
            if(network_state && location_state) {
                Intent i = new Intent(getApplicationContext(), InputActivity.class);
                i.putExtra("location", location);
                startActivity(i);
                finish();
            }else {
                Toast.makeText(c,"Network error", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public boolean isNetworkOnline() {
        boolean status=false;
        try{
            ConnectivityManager cm = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getNetworkInfo(0);
            if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
                status= true;
            }else {
                netInfo = cm.getNetworkInfo(1);
                if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
                    status= true;
            }
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return status;
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        //closing transition animations
        overridePendingTransition(R.anim.activity_open_scale,R.anim.activity_close_translate);
    }

    public boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}
